package org.example.petitionplatformsystem.service.Impl;

import org.example.petitionplatformsystem.dao.UsersRepository;
import org.example.petitionplatformsystem.dao.model.Users;
import org.example.petitionplatformsystem.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersRepository usersRepository;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Override
    public Users GetUsersById(long id) {

        return usersRepository.findById(id).orElse(null);
    }

    @Override
    public Users AddUsers(Users user) {
        return usersRepository.save(user);
    }

    @Override
    public void DeleteUsers(long userId) {
      usersRepository.deleteById(userId);
    }

    @Override
    public Users UpdateUsers(Users user) {
       return usersRepository.save(user);
    }

    @Override
    public List<Users> GetAllUsers() {
        return usersRepository.findAll();
    }

    @Override
    public Users GetUsersByPhoneNumber(String phoneNumber) {
        return usersRepository.findByPhoneNumber(phoneNumber);
    }

    @Override
    public void UpdateUsersPassword(Long userId, String password) {
        String sql = "update users set password = ? where userId = ?";
        jdbcTemplate.update(sql, password, userId);
    }
    @Override
    public boolean onlyOnePhoneNumber(String phoneNumber){
        String sql = "select exists (select 1 from users where phone_Number = ?);";

        return jdbcTemplate.queryForObject(sql, Boolean.class, phoneNumber);
    }
}
